package com.hui.platform.falseworkapi.service.base.sms.controller;

import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.hui.platform.falseworkapi.common.security.annotation.SecurityIgnored;
import com.hui.platform.falseworkapi.common.web.annotation.ApiResult;
import com.hui.platform.falseworkapi.service.base.sms.constant.SmsTypeEnum;
import com.hui.platform.falseworkapi.service.base.sms.service.AliSmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;


/**
 * 	短信管理
 * @author hui
 *
 */
@Api(value="短信管理")
@RestController
@ApiResult
@CrossOrigin
@RequestMapping("/sms")
public class AliSmsController {

    @Autowired
    private AliSmsService aliSmsService;

    @Autowired
    private RedisTemplate redisTemplate;


    @ApiOperation(value="身份验证验证码")//验证码${code}，您正在进行身份验证，打死不要告诉别人哦！
    @GetMapping("/idCheckSms")
    @SecurityIgnored
    public QuerySendDetailsResponse idCheckSms(@ApiParam(value="手机号码，发送国际/港澳台消息时，接收号码格式为：国际区号+号码", required = true) @RequestParam String phoneNumbers) throws ClientException, InterruptedException  {
        String signName = "MkTail";
        String templateCode = "SMS_167675113";
        String smscode = getSmsCode();
        String templateParam = "{ \"code\":" + smscode + "}";
        SendSmsResponse response = aliSmsService.sendSms(phoneNumbers,signName,templateCode,templateParam);

        Thread.sleep(5);
        if(response.getCode() != null && response.getCode().equals("OK")) {
            QuerySendDetailsResponse querySendDetailsResponse = aliSmsService.querySendDetails(response.getBizId(), phoneNumbers);
            redisTemplate.opsForValue().set(SmsTypeEnum.CHECKIDENTIFY.getType() + phoneNumbers,smscode,5,TimeUnit.MINUTES);
            return querySendDetailsResponse;
        }else {
            return null;
        }
    }

    private String getSmsCode(){
        String csmsCode= String.valueOf(Math.random());
        csmsCode = csmsCode.substring(2, 8);
        if(csmsCode.startsWith("0")){
            csmsCode = csmsCode.replace("0","3");
        }
        return csmsCode;
    }



}
